package com.dlc.apk.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class IOUtils {
    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        Throwable var2 = null;

        byte[] var3;
        try {
            copy(input, output);
            var3 = output.toByteArray();
        } catch (Throwable var12) {
            var2 = var12;
            throw var12;
        } finally {
            if (var2 != null) {
                try {
                    output.close();
                } catch (Throwable var11) {
                    var2.addSuppressed(var11);
                }
            } else {
                output.close();
            }
        }

        return var3;
    }

    public static int copy(InputStream input, OutputStream output) throws IOException {
        long count = copyLarge(input, output);
        return count > 2147483647L ? -1 : (int) count;
    }

    /**
     * (2147483647L+1)/4096=2的19次方，为什么是4096呢？
     * 1 byte = 8 bit ，bit是0和1表示，即byte的取值范围是256，
     * 请问为什么byte[4096]标注的是4096，有什么说法？
     */
    public static long copyLarge(InputStream input, OutputStream output) throws IOException {
        return copy(input, output, 4096);
    }

    public static long copy(InputStream input, OutputStream output, int bufferSize) throws IOException {
        return copyLarge(input, output, new byte[bufferSize]);
    }

    public static long copyLarge(InputStream input, OutputStream output, byte[] buffer) throws IOException {
        long count;
        int n;
        //input结束的时候读取的是长度是-1
        for (count = 0L; -1 != (n = input.read(buffer)); count += (long) n) {
            output.write(buffer, 0, n);
        }

        return count;
    }
}
